<template>
  <Basic title="延长隔离" :show-dialog="showExtendDialog" @cancel="handleCancel" @confirm="handleConfirmDialog">
    <div class="pt-2">
      <van-field
        v-model="isolate_endtime"
        is-link
        readonly
        name="isolate_endtime"
        label="延长隔离时间"
        placeholder="结束隔离时间"
        input-align="right"
        @click="showCalendar = true"
        label-width="100"
      />
      <van-calendar v-model:show="showCalendar" :min-date="minDate" color="#2e7cff" teleport="body" @confirm="handleConfirmCalendar" />
    </div>
  </Basic>
</template>

<script lang="ts">
import { computed, defineComponent, ref } from 'vue'
import { usePersonStore } from '@/store/person'
import Basic from './Basic.vue'
import { Toast } from 'vant'
import dayjs from 'dayjs'

export default defineComponent({
  name: 'Extend',
  components: {
    Basic
  },
  props: {
    person: {
      type: Object,
      default: () => {}
    },
  },
  setup(props, { emit }) {
    const store = usePersonStore()
    const person = computed(() => props.person)
    const showExtendDialog = computed(() => {
      if(!person.value) return false
      return store.showExtendDialog
    })

    const minDate = computed(() => {
      if(!props.person) return
      const isolate_endtime = props.person && props.person.isolate_endtime
      const [minY, minM, minD] = (isolate_endtime as string).split('-') as any[]
      return new Date(minY, minM-1, minD)
    })

    const isolate_endtime = ref('')
    const showCalendar = ref(false);

    const handleConfirmCalendar = (date:any) => {
      isolate_endtime.value = dayjs(date).format('YYYY-MM-DD');
      showCalendar.value = false;
    };

    const handleCancel = () => {
      store.setShowExtendDialog(false)
    }

    const handleConfirmDialog = async () => {
      if (!isolate_endtime.value) return Toast.fail('请选择隔离结束时间');
      const {code, data} = await store.extendPerson({ isolate_endtime: dayjs(isolate_endtime.value).format('YYYY-MM-DD') }, props.person.id) as any
      if(code === 200) {
        store.setShowExtendDialog(false)
        emit('success', data)
      }
    }

    return {
      isolate_endtime,
      minDate,
      showExtendDialog,
      handleConfirmCalendar,
      showCalendar,
      handleCancel,
      handleConfirmDialog
    };
  }
})
</script>

